<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form class="antd-modal-form" v-bind="formItemLayout" ref="formRef" name="ContractAmountInfoForm">
          <a-row>
						<a-col :span="24">
							<a-form-item label="合同总额" v-bind="validateInfos.amount" id="ContractAmountInfo-amount" name="amount">
								<a-input-number v-model:value="formData.amount" placeholder="请输入合同总额" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="优惠总额" v-bind="validateInfos.discountAmount" id="ContractAmountInfo-discountAmount" name="discountAmount">
								<a-input-number v-model:value="formData.discountAmount" placeholder="请输入优惠总额" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="实际总额" v-bind="validateInfos.realAmount" id="ContractAmountInfo-realAmount" name="realAmount">
								<a-input-number v-model:value="formData.realAmount" placeholder="请输入实际总额" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="收款类型" v-bind="validateInfos.paymentType" id="ContractAmountInfo-paymentType" name="paymentType">
								<j-dict-select-tag v-model:value="formData.paymentType" dictCode="payment_type" placeholder="请选择收款类型"  allow-clear :show-arrow="!disabled"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="开票类型" v-bind="validateInfos.trickType" id="ContractAmountInfo-trickType" name="trickType">
								<j-dict-select-tag v-model:value="formData.trickType" dictCode="trick_type" placeholder="请选择开票类型"  allow-clear :show-arrow="!disabled"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="运杂费" v-bind="validateInfos.freightCharge" id="ContractAmountInfo-freightCharge" name="freightCharge">
								<a-input-number v-model:value="formData.freightCharge" placeholder="请输入运杂费" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="账期" v-bind="validateInfos.billingPeriod" id="ContractAmountInfo-billingPeriod" name="billingPeriod">
								<a-input v-model:value="formData.billingPeriod" placeholder="请输入账期"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, onMounted, inject, defineProps, unref, computed } from 'vue';
  import { defHttp } from '/@/utils/http/axios';

  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { contractAmountInfoSaveOrUpdate } from '../Contracts.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { useMessage } from '/@/hooks/web/useMessage';

  //接收主表id
  const mainId = inject('mainId');
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
        amount: undefined,
        discountAmount: undefined,
        realAmount: undefined,
        paymentType: '',   
        trickType: '',   
        freightCharge: undefined,
        billingPeriod: '',   
  });

  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const { createMessage } = useMessage();
  //表单验证
  const validatorRules = {
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formBpm: { type: Boolean, default: true },
    formData: { type: Object, default: () => ({}) }
  });

  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData?.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 5 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
  };
  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    try {
      // 触发表单验证
      await validate();
    } catch (err:any) {
      if (err.errorFields) {
        const firstField = err.errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(err);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
   
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if (unref(mainId)) {
      model['contractNumber'] = unref(mainId);
    }
    await contractAmountInfoSaveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res && res.success) {
          createMessage.success('保存成功');
          emit('ok');
        } else {
          const msg = (res && (res.message || res.msg)) || '保存失败';
          createMessage.error(msg);
        }
      })
      .catch((e:any) => {
        const msg = e?.response?.data?.message || e?.message || '请求失败';
        createMessage.error(msg);
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
